const Nightmare = require('nightmare')
const redis = require("redis")
var Minio = require('minio')

var minioClient = new Minio.Client({
    endPoint: '10.10.117.84',
    port: 9090,
    useSSL: false,
    accessKey: 'rzx',
    secretKey: 'Rzx@1218'
});

config_param = {
    host: "10.10.117.81",
    port: 6379,
    password: "Surfilter@1218",
    db: 0
}

const client = redis.createClient(config_param)

const testKey = "test-key-001"

client.lpush(testKey, [ "https://www.csdn.net/"])


var metaData = {
    'Content-Type': 'application/octet-stream',
    'X-Amz-Meta-Testing': 1234,
    'example': 5678
}
// Using fPutObject API upload your file to the bucket europetrip.

function wait(ms) {
    return new Promise(resolve => setTimeout(() => resolve(), ms));
};

/**
 * 
 *  初步实现的从redis推入数据，到此处截图，再上传至minio的整个流程
 *  TODO  下一步测试，打包镜像过程
 * 
 * */ 
function myFunc(){
    client.rpop(testKey, async function(err, resp) {
        if (err) throw err;
        if(resp){
            const site_url = resp;
            console.log("已接收网站：", site_url);

            const prefixName = site_url.split(".")[1]
            const currentData = Math.floor(Date.now())
            const filePath = prefixName + '-' + currentData + '.png'

            console.log("开始网站截图");
            const nightmare = Nightmare({ show: false, width: 1920, height:1080 })
            nightmare
                .goto(site_url)
                .screenshot(filePath)
                .end()
                .then(()=>{
                    console.log(prefixName + "网站截图完成，准备上传文件");
                    minioClient.fPutObject('test02', filePath, filePath, metaData, function(err, etag) {
                        if (err) return console.log(err)
                        console.log('网站截图上传成功。') 
                        myFunc()                     
                      });
                })
                .catch(error => {
                    console.error('网站截图失败:', error)
                })
        }else{
            console.log('未获取网站地址，等待5s再执行')   
            await wait(5000)
            myFunc()
        }       
    })
}

// 每1s执行一次，从redis队列获取数据（可以设置每5s执行一次，从redis队列获取数据，获取成功则继续执行）
// setInterval(myFunc, 1000);
myFunc()




//屏幕宽度尺寸 1920x1080、1600x900、800x600





// 'https://www.baidu.com/'

const myUrl = "https://www.csdn.net/"


//console.log(prefixName)




